package xyz.yuzegod.megawalls.nms;

import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import net.minecraft.server.v1_8_R3.*;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;

import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;

public class CustomCannonball extends EntityArmorStand
{
    public double dirX;
    public double dirY;
    public double dirZ;
    private int e;
    private int f;
    private int g;
    private Block h;
    private boolean i;
    private int ar;
    private int as;
    private Player shooter;
    
    public CustomCannonball(final World world, final double d0, final double d1, final double d2) {
        super(world);
        this.e = -1;
        this.f = -1;
        this.g = -1;
        this.setPosition(d0, d1, d2);
        final ArmorStand as = (ArmorStand)this.getBukkitEntity();
        as.setGravity(true);
        as.setVisible(false);
        as.setHelmet(createSkull());
        this.setDirection(d0, d1, d2);
    }
    
    private static ItemStack createSkull() {
        final ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short)3);
        final SkullMeta meta = (SkullMeta)item.getItemMeta();
        final GameProfile gp = new GameProfile(UUID.randomUUID(), (String)null);
        gp.getProperties().put("textures",new Property("textures", new String("eyJ0aW1lc3RhbXAiOjE1NDk0Mzc4NDUyNzYsInByb2ZpbGVJZCI6ImRhNzQ2NWVkMjljYjRkZTA5MzRkOTIwMTc0NDkxMzU1IiwicHJvZmlsZU5hbWUiOiJLaWRTbGljZXIiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2VjMzk1Mzc0OTc5MGQ1M2NlODkwZmVlN2UzMDY5NzQwNTIwZmJiMjQyNjJmY2VlNWZjNjAwNGNmODcyMDVhZDkifX19")));
        try {
            final Field field = meta.getClass().getDeclaredField("profile");
            field.setAccessible(true);
            field.set(meta, gp);
        }
        catch (Exception ex) {}
        item.setItemMeta((ItemMeta)meta);
        return item;
    }
    
    public Player getShooter() {
        return this.shooter;
    }
    
    public void setShooter(final Player shooter) {
        this.shooter = shooter;
    }
    
    public void setDirection(double d0, double d1, double d2) {
        d0 += this.random.nextGaussian() * 0.4;
        d1 += this.random.nextGaussian() * 0.4;
        d2 += this.random.nextGaussian() * 0.4;
        final double d3 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2);
        this.dirX = d0 / d3 * 0.1;
        this.dirY = d1 / d3 * 0.1;
        this.dirZ = d2 / d3 * 0.1;
    }
    
    public boolean damageEntity(final DamageSource damagesource, final float f) {
        return true;
    }
    
    public void t_() {
        if (!this.world.isClientSide && ((this.shooter != null && this.shooter.isDead()) || !this.world.isLoaded(new BlockPosition((Entity)this)))) {
            this.die();
        }
        else {
            super.t();
            if (this.i) {
                if (this.world.getType(new BlockPosition(this.e, this.f, this.g)).getBlock() == this.h) {
                    ++this.ar;
                    if (this.ar == 600) {
                        this.die();
                    }
                    return;
                }
                this.i = false;
                this.motX *= this.random.nextFloat() * 0.2f;
                this.motY *= this.random.nextFloat() * 0.2f;
                this.motZ *= this.random.nextFloat() * 0.2f;
                this.ar = 0;
                this.as = 0;
            }
            else {
                ++this.as;
            }
            Vec3D vec3d = new Vec3D(this.locX, this.locY, this.locZ);
            Vec3D vec3d2 = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ);
            MovingObjectPosition movingobjectposition = this.world.rayTrace(vec3d, vec3d2);
            vec3d = new Vec3D(this.locX, this.locY, this.locZ);
            vec3d2 = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ);
            if (movingobjectposition != null) {
                vec3d2 = new Vec3D(movingobjectposition.pos.a, movingobjectposition.pos.b, movingobjectposition.pos.c);
            }
            Entity entity = null;
            final List<Entity> list = (List<Entity>)this.world.getEntities((Entity)this, this.getBoundingBox().a(this.motX, this.motY, this.motZ).grow(1.0, 1.0, 1.0));
            double d0 = 0.0;
            for (int i = 0; i < list.size(); ++i) {
                final Entity entity2 = list.get(i);
                if (entity2.ad() && (!entity2.k((Entity)((CraftPlayer)this.shooter).getHandle()) || this.as >= 25)) {
                    final float f = 0.3f;
                    final AxisAlignedBB axisalignedbb = entity2.getBoundingBox().grow((double)f, (double)f, (double)f);
                    final MovingObjectPosition movingobjectposition2 = axisalignedbb.a(vec3d, vec3d2);
                    if (movingobjectposition2 != null) {
                        final double d2 = vec3d.distanceSquared(movingobjectposition2.pos);
                        if (d2 < d0 || d0 == 0.0) {
                            entity = entity2;
                            d0 = d2;
                        }
                    }
                }
            }
            if (entity != null) {
                movingobjectposition = new MovingObjectPosition(entity);
            }
            if (movingobjectposition != null) {
                this.a(movingobjectposition);
            }
            this.locX += this.motX;
            this.locY += this.motY;
            this.locZ += this.motZ;
            final float f2 = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ);
            this.yaw = (float)(MathHelper.b(this.motZ, this.motX) * 180.0 / 3.141592741012573) + 90.0f;
            this.pitch = (float)(MathHelper.b((double)f2, this.motY) * 180.0 / 3.141592741012573) - 90.0f;
            while (this.pitch - this.lastPitch < -180.0f) {
                this.lastPitch -= 360.0f;
            }
            while (this.pitch - this.lastPitch >= 180.0f) {
                this.lastPitch += 360.0f;
            }
            while (this.yaw - this.lastYaw < -180.0f) {
                this.lastYaw -= 360.0f;
            }
            while (this.yaw - this.lastYaw >= 180.0f) {
                this.lastYaw += 360.0f;
            }
            this.pitch = this.lastPitch + (this.pitch - this.lastPitch) * 0.2f;
            this.yaw = this.lastYaw + (this.yaw - this.lastYaw) * 0.2f;
            float f3 = 0.95f;
            if (this.V()) {
                for (int j = 0; j < 4; ++j) {
                    final float f4 = 0.25f;
                    this.world.addParticle(EnumParticle.WATER_BUBBLE, this.locX - this.motX * f4, this.locY - this.motY * f4, this.locZ - this.motZ * f4, this.motX, this.motY, this.motZ, new int[0]);
                }
                f3 = 0.8f;
            }
            this.motX += this.dirX;
            this.motY += this.dirY;
            this.motZ += this.dirZ;
            this.motX *= f3;
            this.motY *= f3;
            this.motZ *= f3;
            this.world.addParticle(EnumParticle.SMOKE_NORMAL, this.locX, this.locY + 0.5, this.locZ, 0.0, 0.0, 0.0, new int[0]);
            this.setPosition(this.locX, this.locY, this.locZ);
        }
    }
    
    public float a(final Explosion explosion, final World world, final BlockPosition blockposition, final IBlockData iblockdata) {
        float f = super.a(explosion, world, blockposition, iblockdata);
        final Block block = iblockdata.getBlock();
        if (EntityWither.a(block)) {
            f = Math.min(0.8f, f);
        }
        return f;
    }
    
    protected void a(final MovingObjectPosition movingobjectposition) {
        if (!this.world.isClientSide) {
            if (movingobjectposition.entity != null) {
                boolean didDamage;
                if (this.shooter != null) {
                    didDamage = movingobjectposition.entity.damageEntity(DamageSource.projectile((Entity)this, (Entity)((CraftPlayer)this.shooter).getHandle()), 8.0f);
                }
                else {
                    didDamage = movingobjectposition.entity.damageEntity(DamageSource.MAGIC, 5.0f);
                }
                if (didDamage && movingobjectposition.entity instanceof EntityLiving) {
                    byte b0 = 0;
                    if (this.world.getDifficulty() == EnumDifficulty.NORMAL) {
                        b0 = 10;
                    }
                    else if (this.world.getDifficulty() == EnumDifficulty.HARD) {
                        b0 = 40;
                    }
                    if (b0 > 0) {
                        ((EntityLiving)movingobjectposition.entity).addEffect(new MobEffect(MobEffectList.WITHER.id, 20 * b0, 1));
                    }
                }
            }
            final ExplosionPrimeEvent event = new ExplosionPrimeEvent((org.bukkit.entity.Entity)this.getBukkitEntity(), 1.0f, false);
            this.world.getServer().getPluginManager().callEvent((Event)event);
            if (!event.isCancelled()) {
                this.world.createExplosion((Entity)this, this.locX, this.locY, this.locZ, event.getRadius(), event.getFire(), this.world.getGameRules().getBoolean("mobGriefing"));
            }
            this.die();
        }
    }
    
    public void b(final NBTTagCompound nbttagcompound) {
        nbttagcompound.setShort("xTile", (short)this.e);
        nbttagcompound.setShort("yTile", (short)this.f);
        nbttagcompound.setShort("zTile", (short)this.g);
        final MinecraftKey minecraftkey = (MinecraftKey)Block.REGISTRY.c(this.h);
        nbttagcompound.setString("inTile", (minecraftkey == null) ? "" : minecraftkey.toString());
        nbttagcompound.setByte("inGround", (byte)(byte)(this.i ? 1 : 0));
        nbttagcompound.set("power", (NBTBase)this.a(new double[] { this.dirX, this.dirY, this.dirZ }));
        nbttagcompound.set("direction", (NBTBase)this.a(new double[] { this.motX, this.motY, this.motZ }));
    }
    
    public void a(final NBTTagCompound nbttagcompound) {
        this.e = nbttagcompound.getShort("xTile");
        this.f = nbttagcompound.getShort("yTile");
        this.g = nbttagcompound.getShort("zTile");
        if (nbttagcompound.hasKeyOfType("inTile", 8)) {
            this.h = Block.getByName(nbttagcompound.getString("inTile"));
        }
        else {
            this.h = Block.getById(nbttagcompound.getByte("inTile") & 0xFF);
        }
        this.i = (nbttagcompound.getByte("inGround") == 1);
        if (nbttagcompound.hasKeyOfType("power", 9)) {
            final NBTTagList nbttaglist = nbttagcompound.getList("power", 6);
            this.dirX = nbttaglist.d(0);
            this.dirY = nbttaglist.d(1);
            this.dirZ = nbttaglist.d(2);
        }
        else if (nbttagcompound.hasKeyOfType("direction", 9)) {
            final NBTTagList nbttaglist = nbttagcompound.getList("direction", 6);
            this.motX = nbttaglist.d(0);
            this.motY = nbttaglist.d(1);
            this.motZ = nbttaglist.d(2);
        }
        else {
            this.die();
        }
    }
}
